<?php

/**
 * @Author: wuchenge
 * @Date:   2022-04-19 14:19:03
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Libraries;

use Illuminate\Support\Facades\Cache;
use Storage;

class Qiniu
{
    const KEY = 'qiniu_token';

    public static function getToken()
    {
        $file_name = self::uuid();
        $full_path = config('app.name') . '/' . $file_name;

        $token = Cache::get(self::KEY);

        if (!$token) {
            try {
                $disk  = Storage::disk('qiniu');
                $token = $disk->uploadToken();
            } catch (\Exception $e) {
                return [
                    'status'  => false,
                    'message' => '获取token失败' . $e->getMessage(),
                ];
            }

            // 缓存起来
            Cache::put(self::KEY, $token, 3599);

        }

        return [
            'status' => true,
            'data'   => [
                'token'            => $token,
                'key'              => $full_path,
                'qiniu_url_prefix' => config('filesystems.disks.qiniu.domains.default'),
            ],
        ];

    }

    /**
     * 获取唯一
     * @return [type] [description]
     */
    public static function uuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars, 0, 8);
        $uuid .= substr($chars, 8, 4);
        $uuid .= substr($chars, 12, 4);
        $uuid .= substr($chars, 16, 4);
        $uuid .= substr($chars, 20, 12);
        return $uuid;
    }
}
